<?php

namespace api\modules\tsline\models;

use Yii;
use common\base\Model;
use common\models\user\UserCollect;
use common\models\tsline\TslineArticle;

class ArticleCollectForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $article_id
     * @var integer 文章ID
     */
    public $article_id;
    private $_article;

    /**
     * @return array validation rules
     */
    public function rules() {
        return [
            [['user_id', 'article_id'], 'integer'],
            [['article_id'], 'required'],
            [['article_id'], 'validateArticle'],
        ];
    }

    /**
     * Validates the Article is exisit.
     * @param string $attribute the attribute currently being validated
     */
    public function validateArticle($attribute) {
        if (!$this->hasErrors()) {
            $_model = $this->getArticle();
            if (!$_model) {
                $this->addError($attribute, '文章不存在');
            }
        }
    }

    protected function getArticle() {
        return $this->_article = TslineArticle::findOne($this->article_id);
    }

    /**
     * 保存点赞信息
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('参数校验失败');
        }
        $model = UserCollect::findOrNew([
            'model' => UserCollect::MODEL_ARTICLE,
            'model_id' => $this->article_id,
            'user_id' => $this->user_id,
        ]);
        if ($model->isNewRecord) {
            return $model->save();
        }
        return !$model->delete();
    }

}
